package com.zbmsg.group.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zbmsg.group.bean.Group;
import com.zbmsg.group.service.IGroupService;
import com.zbmsg.server.Global;
import com.zbmsg.user.bean.User;
import com.zbmsg.user.service.IUserService;
import com.zbmsg.utils.id.IdWorker;

import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

@Service("groupService")
public class GroupServiceImpl implements IGroupService {

	@Autowired
	private IUserService userService;

	@Override
	public String add(Group group) throws Exception {
		String key = String.valueOf(IdWorker.getInstance().nextId());
		group.setGroupId(key);
		Global.channelGroups.put(key, new DefaultChannelGroup(GlobalEventExecutor.INSTANCE));
		Global.groups.put(key, group);
		return key;
	}

	@Override
	public void clean(String groupId) throws Exception {
		if (StringUtils.isEmpty(groupId)) {
			return;
		}
		ChannelGroup groups = Global.channelGroups.get(groupId);
		if (groups == null) {
			return;
		}
		if (groups.size() > 0) {
			return;
		}
		Global.groups.remove(groupId);
		Global.channelGroups.remove(groupId);
	}

	@Override
	public Group getGroup(String groupId) throws Exception {
		return Global.groups.get(groupId);
	}

	@Override
	public Group isCreateGroup(String userId) throws Exception {
		User user = this.userService.getUserByUserId(userId);
		if (StringUtils.isEmpty(user.getGroupId())) {
			return null;
		}
		Group group = this.getGroup(user.getGroupId());
		if (!group.getUserId().equals(user.getId())) {
			return null;
		}
		return group;
	}

	@Override
	public List<Group> listWithGroups() throws Exception {
		List<Group> groupList = new ArrayList<>();
		for (String key : Global.groups.keySet()) {
			groupList.add(Global.groups.get(key));
		}
		return groupList;
	}

}
